More array methods
In this lesson, we'll take a look at three array methods.
Array map
You can transform an array into another using the .map(callback)
method. Here are some examples,
[4, 2, 5, 8] became [8, 4, 10, 16]. Every item in the original array was doubled.
["css", "html"] became ["CSS", "HTML"]. Every item in the original array was capitalised.
You'll notice that you always get back an array with the same number of items as the original array, but each item has most likely been transformed in some way.
The transformation in the first example is that we multiply every number by 2.
The transformation in the second example is that we call .toUpperCase()
on each item.
Let's look at how we can put these changes into action:
const numbers = [4, 2, 5, 8];
const square = numbers.map(function (number) {
return number * 2;
});
console.log(square); // [8, 4, 10, 16]
and
const words = ["css", "html"];
const upperWords = words.map(function (word) {
return word.toUpperCase();
});
console.log(square); // ["CSS", "HTML"]
If you omit the return
statement within the callback function, you will get the following array [undefined, undefined]
. Because you're returning undefined
for each item in the original array (["css", "html"]
), the end result will be [undefined, undefined]
.
Array includes
The array .includes(item)
method is one of the most basic array methods because it takes an item instead of a callback and returns true
if the item exists in the array and false
otherwise.
Here's an example:
const groceries = ["Apple", "Peach", "Tomato"];
groceries.includes("Tomato"); // true
groceries.includes("Bread"); // false
Array join
The array.toString()
will convert the given array to a string automatically. JavaScript will automatically invoke the .toString()
method, which returns a string containing the array elements separated by commas.
This is how it works,
const fruits = ["Apple", "Orange", "Tomato"];
groceries.toString(); // "Apple,Orange,Tomato"
However, there is a drawback, you cannot customise the token that is inserted between the array items, which is the comma
, character in array.toString()
method.
If you want to modify the token, you can use the .join(token)
method:
const groceries = ["Apple", "Peach", "Tomato"];
groceries.join("; "); // "Apple; Peach; Tomato"
groceries.join(" . "); // "Apple . Peach . Tomato"